﻿CREATE PROCEDURE [maint].[RefreshDbConfig]

AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @RC int, @ERROR int
	SET @RC = 0

	BEGIN TRAN

	TRUNCATE TABLE [config].[DbMaintenance]
	SET @ERROR = @@ERROR
	IF(@ERROR <> 0)
		GOTO ERROR_HANDLER

	DECLARE DB_CUR CURSOR LOCAL FAST_FORWARD FOR(
		SELECT [name]
		FROM master.dbo.sysdatabases
		WHERE ([name] NOT IN (N'model', N'tempdb'))
	)
	OPEN DB_CUR

	DECLARE @DbName sysname
	FETCH NEXT FROM DB_CUR INTO @DbName
	WHILE(@@FETCH_STATUS = 0)
		BEGIN
			EXEC @RC = maint.ConfigDbMaintenance @DbName
			IF(@RC <> 0)
				GOTO ERROR_HANDLER

			FETCH NEXT FROM DB_CUR INTO @DbName
		END

	IF(@@TRANCOUNT > 0)
		COMMIT TRAN

	GOTO EXIT_PROC

ERROR_HANDLER:
	IF(@@TRANCOUNT > 0)
		ROLLBACK TRAN

	IF(@RC = 0)
		SET @RC = @ERROR
EXIT_PROC:
	RETURN(@RC)
END